package com.mengdie.shuidi.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.utils.EmptyUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.BitmapCallback;
import com.lzy.okgo.callback.StringCallback;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.AppManager;
import com.mengdie.shuidi.OkHeader;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.api.network.StringDialogCallback;
import com.mengdie.shuidi.helper.UIHelper;
import com.mengdie.shuidi.manager.MDAccountMgr;
import com.mengdie.shuidi.manager.MDUserMgr;
import com.mengdie.shuidi.model.BaseModel;
import com.mengdie.shuidi.model.ExceedUserEnetity;
import com.mengdie.shuidi.model.SessionEnetity;
import com.mengdie.shuidi.model.UserEnetity;
import com.mengdie.shuidi.utils.DeviceUuidFactory;
import com.mengdie.shuidi.utils.ToastUtil;
import com.mengdie.shuidi.utils.common.MD5Util;
import com.mengdie.shuidi.utils.common.RegularUtils;
import com.mengdie.shuidi.widgets.ButtonTimer;
import com.orhanobut.logger.Logger;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by apple on 16/10/13.
 */

public class RegistBindPhoneActivity extends BaseActivity {


    @Bind(R.id.rl_generic_back)
    RelativeLayout mRlGenericBack;
    @Bind(R.id.tv_generic_title)
    TextView mTvGenericTitle;
    @Bind(R.id.et_bind_phone)
    EditText mEtBindPhone;
    @Bind(R.id.et_bind_code)
    EditText mEtBindCode;
    @Bind(R.id.bt_bind_code)
    ButtonTimer mBtBindCode;
    //    @Bind(R.id.et_bind_local_code)
//    EditText mEtBindLocalCode;
//    @Bind(R.id.iv_bind_local_code)
//    ImageView mIvBindLocalCode;
    @Bind(R.id.tv_bind_submit)
    TextView mTvBindSubmit;
    @Bind(R.id.et_bind_verfiy)
    EditText mEtBindVerfiy;
    @Bind(R.id.iv_bind_verfiy)
    ImageView mIvBindVerfiy;
    private String name;
    private String phone;
    private String username;

    @Bind(R.id.next_head)
    TextView mNextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist_bind_phone);
        ButterKnife.bind(this);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            name = bundle.getString("name");
            username = bundle.getString("username");
            password = bundle.getString("pass");
        } else {
            name = MDAccountMgr.getInstance().getLoginName();
        }

        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }

    public void init() {
        mTvGenericTitle.setText("绑定手机号");
        mNextView.setVisibility(View.VISIBLE);
    }

    @OnClick({R.id.rl_generic_back, R.id.bt_bind_code, R.id.tv_bind_submit, R.id.next_head, R.id.iv_bind_verfiy})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_generic_back:
                onBackPressed();
                break;
            case R.id.bt_bind_code:
                phone = mEtBindPhone.getText().toString();
                String verfiy = mEtBindVerfiy.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtil.showToast(getString(R.string.et_is_phone_empty));
                } else {
                    if (RegularUtils.isMobileExact(phone)) {
                        if (EmptyUtils.isNotEmpty(verfiy)) {
                            getCode(phone, verfiy);
                        } else {
                            ToastUtil.showToast(getString(R.string.et_is_verify_empty));
                        }
                    } else {
                        ToastUtil.showToast("手机号格式不正确!");
                    }
                }
                break;
            case R.id.iv_bind_verfiy:
                getImgVerify();
                break;
            case R.id.tv_bind_submit:
                phone = mEtBindPhone.getText().toString();
                String code = mEtBindCode.getText().toString();
                if (TextUtils.isEmpty(phone) && TextUtils.isEmpty(code)) {
                    ToastUtil.showToast(getResources().getString(R.string.et_is_phone_empty));
                } else {
                    if (RegularUtils.isMobileExact(phone)) {
                        if (EmptyUtils.isNotEmpty(code)) {
                            setPhone(phone, code);
                        } else {
                            ToastUtil.showToast(getString(R.string.et_is_code_empty));
                        }
                    } else {
                        ToastUtil.showToast("手机号格式不正确!");
                    }
                }
                break;
            case R.id.next_head:

                login(name, password);

                break;
        }
    }

    public void getImgVerify() {
        OkGo.post(AppContext.getInstance().getBaseUrl() + "account/verify").tag("verify")
                .execute(new BitmapCallback() {
                    @Override
                    public void onSuccess(Bitmap bitmap, Call call, Response response) {
                        mIvBindVerfiy.setImageBitmap(bitmap);

                    }
                });
    }

    @Override
    public void onStart() {
        super.onStart();
        getImgVerify();
    }

    public void getCode(String phone, String verfiy) {
        HashMap<String, String> map = new HashMap<>();
        map.put("num", phone);
        map.put("code", "rst_pass");
        map.put("verify", verfiy);
        JSONObject json = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHead(this)).post(AppContext.getInstance().getBaseUrl() + "account/get_code_new")
                .tag(RegistBindPhoneActivity.this)
                .upJson(json.toString())
                .execute(new StringDialogCallback(RegistBindPhoneActivity.this, "加载中...", true) {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        if (baseModel.getRet().equals("0")) {
                            mBtBindCode.setTimes(60);
                            mBtBindCode.setType("1");
                            if (!mBtBindCode.isRun()) {
                                mBtBindCode.beginRun();
                                mBtBindCode.setEnabled(false);
                            }
                            ToastUtil.showToast(baseModel.getMsg());
                        } else {
                            getImgVerify();
                            ToastUtil.showToast(baseModel.getMsg());
                        }
                    }
                });

    }

    private String password;

    public void setPhone(String phone, String code) {
        HashMap map = new HashMap();
        map.put("version", AppContext.version);
        map.put("username", username);
        map.put("phone", phone);
        map.put("phone_code", code);
        map.put("client_id", MD5Util.md5(new DeviceUuidFactory(AppContext.getInstance()).getDeviceUuid().toString()));
        JSONObject json = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHead(this)).post(AppContext.getInstance().getBaseUrl() + "account/set_phone_bind")
                .tag(RegistBindPhoneActivity.this)
                .upJson(json.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModel = gson.fromJson(s, BaseModel.class);
                        Logger.e("绑定手机号: " + baseModel.toString());
                        if (baseModel.getRet().equals("0")) {
                            Intent bind = new Intent(RegistBindPhoneActivity.this, BindPhoneSuccessActivity.class);
                            bind.putExtra("name", name);
                            bind.putExtra("pass", password);
                            bind.putExtra("regist", true);
                            startActivity(bind);
                            finish();
                        } else {
                            getImgVerify();
                            ToastUtil.showToast(baseModel.getMsg());
                        }
                    }

                });
    }

    /**
     * 登录
     *
     * @param name
     * @param password
     */
    public void login(final String name, final String password) {



        HashMap<String, String> map = new HashMap<>();
        map.put("username", name);
        map.put("password", password);
        map.put("client_id", MD5Util.md5(new DeviceUuidFactory(AppContext.getInstance()).getDeviceUuid().toString()));
        map.put("device_token", MDAccountMgr.getInstance().getDeviceToken());
        JSONObject jsonObject = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHead(this)).post(AppContext.getInstance().getBaseUrl() + "account/login_new")
                .tag(this)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModels = gson.fromJson(s, BaseModel.class);
                        if (baseModels.getRet().equals("0")) {
                            Type userType = new TypeToken<BaseModel<SessionEnetity>>() {
                            }.getType();
                            BaseModel<SessionEnetity> baseModel;
                            try {
                                baseModel = gson.fromJson(s, userType);
                            } catch (JsonSyntaxException e) {
                                baseModel = gson.fromJson(s, BaseModel.class);
                            }
                            SessionEnetity sessionInfo = baseModel.getData();
                            MDAccountMgr.getInstance().setSessionId(sessionInfo.getSession());
                            UserEnetity user = sessionInfo.getUserInfo();
                            MDUserMgr.getInstance().setAvatar(user.getAvatar());
                            MDUserMgr.getInstance().setAwardFlag(user.getAward_flag());
                            MDUserMgr.getInstance().setId(user.getId());
                            MDUserMgr.getInstance().setUsername(user.getUsername());
                            MDUserMgr.getInstance().setShowUsername(user.getShowUsername());
                            MDUserMgr.getInstance().setNickname(user.getNick_name());
                            MDUserMgr.getInstance().setChange(user.getChange());
                            MDUserMgr.getInstance().setEmail(user.getEmail());
                            MDUserMgr.getInstance().setNum(user.getNum() + "");
                            MDUserMgr.getInstance().setPhone(user.getPhone());
                            MDUserMgr.getInstance().setMoney(Double.valueOf(user.getMoney()));
                            MDUserMgr.getInstance().setLastTime(user.getLast_time());
                            MDUserMgr.getInstance().setLastTimeType(user.getLast_time_type());
                            MDUserMgr.getInstance().setStatus(user.getStatus());
                            MDUserMgr.getInstance().setToken(user.getToken());
                            MDUserMgr.getInstance().setTime(user.getExpire_time_format());
                            MDUserMgr.getInstance().setCoupoum(user.getCoupoum());
                            MDUserMgr.getInstance().setLogin(true);//保存到类

                            MDUserMgr.getInstance().setThreeDayExpire(user.getThreeDayExpire());
                            MDAccountMgr.getInstance().setLogin(true);//保存到内存
                            MDAccountMgr.getInstance().setLoginName(user.getShowUsername());
                            MDAccountMgr.getInstance().setLoginPwd(password);

                            MDAccountMgr.getInstance().setPassowrd(true);
                            MDAccountMgr.getInstance().writeToCache(RegistBindPhoneActivity.this);
                            AppManager.getAppManager().finishActivity(LoginActivity.class);

                            Intent login = new Intent(RegistBindPhoneActivity.this, MainActivity.class);
                            startActivity(login);
                            finish();
                        } else if (baseModels.getRet().equals("1")) {
                            Type exceed = new TypeToken<BaseModel<List<ExceedUserEnetity>>>() {
                            }.getType();
                            BaseModel<List<ExceedUserEnetity>> exceeModel;
                            try {
                                exceeModel = gson.fromJson(s, exceed);
                            } catch (JsonSyntaxException e) {
                                exceeModel = gson.fromJson(s, BaseModel.class);
                            }
                            if (exceeModel.getCode().equals("overtop")) {
                                UIHelper.showTerminal(RegistBindPhoneActivity.this, exceeModel.getData(), UIHelper.LOGIN_DIALOG, "2");
                            } else {
                                ToastUtil.showToast(baseModels.getMsg());
                            }
                        } else {
                            ToastUtil.showToast(baseModels.getMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        ToastUtil.showToast("网络请求失败");

                    }

                });
    }

}
